package com.ruoyi.jzzgl.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.jzzgl.domain.vo.StatisticsVo;
import com.ruoyi.jzzgl.domain.vo.TrendDataVo;
import com.ruoyi.jzzgl.domain.entity.JzzglSkjl;
import com.ruoyi.jzzgl.domain.vo.RankDataVo;
import com.ruoyi.jzzgl.service.JzzglSkjlService;
import com.ruoyi.jzzgl.service.JzzglZdglService;
import com.ruoyi.jzzgl.mapper.JzzglSkjlMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.DateField;

@RequiredArgsConstructor
@RestController
@RequestMapping("/jzzgl/statistics")
public class StatisticsController {

    private final JzzglSkjlService skjlService;
    private final JzzglZdglService zdglService;
    private final JzzglSkjlMapper jzzglSkjlMapper;

    @SaCheckPermission("jzzgl:statistics:list")
    @GetMapping
    public R<StatisticsVo> getStatistics(@RequestParam(required = false) Integer stationId) {
        StatisticsVo vo = new StatisticsVo();

        // 获取顶部卡片数据
        vo.setTotalStations(Math.toIntExact(zdglService.count()));
        vo.setTotalRecords(Math.toIntExact(stationId == null ? skjlService.count() :
            skjlService.count(Wrappers.<JzzglSkjl>lambdaQuery().eq(JzzglSkjl::getStationId, stationId))));
        vo.setTotalElderlyRecords(skjlService.getTotalElderlyRecords(stationId));
        vo.setTodayRecords(skjlService.getTodayRecords(stationId));
        vo.setTodayElderlyRecords(skjlService.getTodayElderlyRecords(stationId));

        // 获取趋势数据
        vo.setTrend(skjlService.getTrendData(stationId, null, null));

        // 获取站点排行
        vo.setRankData(skjlService.getRankData(stationId));

        // 获取年龄分布
        vo.setAgeDistribution(skjlService.getAgeDistribution(stationId));

        // 获取性别比例
        vo.setGenderRatio(skjlService.getGenderRatio(stationId));

        return R.ok(vo);
    }

    @SaCheckPermission("jzzgl:statistics:list")
    @GetMapping("/trend")
    public R<TrendDataVo> getTrendData(@RequestParam(required = false) Integer stationId,@RequestParam(required = false)String timeRange) {
        // 新增时间范围处理
        Date[] dateRange = parseTrendTimeRange(timeRange);
        StatisticsVo.TrendData trendData = skjlService.getTrendData(stationId, dateRange[0], dateRange[1]);

        TrendDataVo vo = new TrendDataVo();
        vo.setDates(trendData.getDates());

        TrendDataVo.Series series = new TrendDataVo.Series();
        series.setTotal(trendData.getTotalCounts());
        series.setElderly(trendData.getElderlyCounts());
        vo.setSeries(series);

        return R.ok(vo);
    }

    @SaCheckPermission("jzzgl:statistics:list")
    @GetMapping("/rank")
    public R<RankDataVo> getRankData(@RequestParam(required = false) Integer stationId,@RequestParam(required = false)String timeRange) {
        // 新增时间范围处理
        Date[] dateRange = parseRankTimeRange(timeRange);
        Date elderlyDate = DateUtil.offset(new Date(), DateField.YEAR, -65);

        List<Map<String, Object>> rankList = stationId == null ?
            jzzglSkjlMapper.selectStationRankWithElderly(5, elderlyDate, dateRange[0], dateRange[1]) :
            jzzglSkjlMapper.selectStationRankWithElderlyById(stationId, elderlyDate, dateRange[0], dateRange[1]);

        List<RankDataVo.StationRank> stations = rankList.stream().map(map -> {
            RankDataVo.StationRank rank = new RankDataVo.StationRank();
            rank.setStationName((String) map.get("stationName"));
            rank.setCount(((Number) map.get("count")).intValue());
            rank.setElderlyCount(((Number) map.get("elderlyCount")).intValue());
            return rank;
        }).collect(Collectors.toList());

        RankDataVo vo = new RankDataVo();
        vo.setStations(stations);
        return R.ok(vo);
    }

    // 新增时间范围解析方法
    private Date[] parseTrendTimeRange(String timeRange) {
        Date now = new Date();
        if ("week".equals(timeRange)) {
            return new Date[]{DateUtil.offsetDay(now, -6), DateUtil.endOfDay(now)};  // 近7天
        } else if ("month".equals(timeRange)) {
            return new Date[]{DateUtil.offsetDay(now, -29), DateUtil.endOfDay(now)}; // 近30天
        } else if ("quarter".equals(timeRange)) {
            return new Date[]{DateUtil.beginOfQuarter(now), DateUtil.endOfQuarter(now)};
        } else if ("year".equals(timeRange)) {
            return new Date[]{DateUtil.beginOfYear(now), DateUtil.endOfYear(now)};
        }
        // 默认返回近7天
        return new Date[]{DateUtil.offsetDay(now, -6), DateUtil.endOfDay(now)};
    }

    // 新增时间范围解析方法
    private Date[] parseRankTimeRange(String timeRange) {
        Date now = new Date();
        if ("today".equals(timeRange)) {
            return new Date[]{DateUtil.beginOfDay(now), DateUtil.endOfDay(now)};
        } else if ("week".equals(timeRange)) {
            return new Date[]{DateUtil.beginOfWeek(now), DateUtil.endOfWeek(now)};
        } else if ("month".equals(timeRange)) {
            return new Date[]{DateUtil.beginOfMonth(now), DateUtil.endOfMonth(now)};
        } else if ("quarter".equals(timeRange)) {
            return new Date[]{DateUtil.beginOfQuarter(now), DateUtil.endOfQuarter(now)};
        } else if ("year".equals(timeRange)) {
            return new Date[]{DateUtil.beginOfYear(now), DateUtil.endOfYear(now)};
        }
        // 默认返回所有时间
        return new Date[]{null, null};
    }
}
